<template>
  <div class="main-box">
    <div class="card content-box w-full">
      <TableContainer
        :page-info="{ current: page, pageSize: pageSize, total: total }"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #searchCard>
          <SearchFrom :search-event="handleSearchEvent" />
        </template>
        <template #btnLeft>
          <el-button v-auth="['user:reset:btn']" type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增
          </el-button>
        </template>
        <el-table :data="[...tableData]" row-key="id" empty-text="暂无数据" v-bind="{ ...gridOptions, ...$attrs }">
          <template #empty>
            <span>暂无数据</span>
          </template>
          <el-table-column
            v-for="item in gridOptions.columns"
            v-bind="{ ...item, ...$attrs }"
            :type="item.type ? item.type : 'default'"
            :label="item.label"
            :prop="item.prop"
            :key="item.prop"
            :width="item.width"
            :fixed="item.fixed ? item.fixed : false"
            :header-align="item.headerAlign ? item.headerAlign : 'left'"
          >
            <template #default="{ row }">
              <el-tag v-if="item.slots == 'status'" :type="row.status ? 'primary' : 'info'">
                {{
                  {
                    1: "启用",
                    0: "停用"
                  }[row.status]
                }}
              </el-tag>
              <div class="w-full flex items-center justify-center" v-if="item.slots === 'controls'">
                <el-button v-auth="['user:reset:btn']" link type="primary" @click="handleEdit(row)">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  修改
                </el-button>
                <el-button link v-auth="['role:status:btn']" type="primary" @click="handleSwitchChange(row)">
                  <el-icon>
                    <Unlock v-if="row.status == '0'" />
                    <Lock v-else />
                  </el-icon>
                  {{ row.status === "0" ? "启用" : "停用" }}
                </el-button>
                <el-button v-auth="['user:reset:btn']" link type="danger" @click="handleDelete(row)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </TableContainer>
    </div>
    <RoleAdd ref="roleAddRef" @close="handleClose"></RoleAdd>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { useComponentRef } from "@/hooks/useComponentRef";
import SearchFrom from "./components/SearchFrom.vue";
import { changePostStatus, deletePost, getPostDetail, getPostList } from "@/api/modules/post";
import { Post } from "@/api/interface";
import { useTableConfig } from "@/hooks/useTable";
import TableContainer from "@/components/TableContainer/index.vue";
import { usePagination } from "alova/client";

const RoleAdd = defineAsyncComponent(() => import("./components/Add.vue"));
const roleAddRef = useComponentRef(RoleAdd);

const queryForm = ref<Post.IPostParams>({});

const { gridOptions } = useTableConfig({
  columns: [
    { prop: "name", label: "岗位名称" },
    { prop: "code", label: "岗位代码" },
    { prop: "status", label: "岗位状态", slots: "status" },
    { prop: "sortOrder", label: "排序" }
  ]
});

const {
  data: tableData,
  page,
  pageSize,
  total,
  send
} = usePagination(
  (page, pageSize) =>
    getPostList({
      current: page,
      size: pageSize,
      ...queryForm.value
    }),
  {
    force: true,
    total: response => response.data?.pager?.total || 0,
    data: response => response.data?.records ?? []
  }
);

const handleSearchEvent = (form: Post.IPostParams) => {
  queryForm.value = form;
  send();
};

const handleAdd = () => {
  roleAddRef.value?.openDialog();
};

const handleEdit = async (row: Post.IPost) => {
  try {
    if (!row.id) return;
    const { data } = await getPostDetail(row.id);
    roleAddRef.value?.openDialog("edit", data);
  } catch (e) {}
};

const handleDelete = async (row: Post.IPost) => {
  try {
    if (!row.id) return;
    await deletePost(row.id);
    ElMessage.success("删除成功");
    await send();
  } catch (e) {}
};
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  page.value = 1;
};
const handleCurrentChange = (current: number) => {
  page.value = current;
};
const handleClose = () => {
  send();
};

const handleSwitchChange = async (row: Post.IPost) => {
  if (!row.id) return;
  try {
    const isEnable = row.status === "1" ? 0 : 1;
    await changePostStatus(row.id, isEnable);
    ElMessage.success(isEnable ? "启用成功" : "停用成功");
    await send();
  } catch (e) {
    row.status = !row.status;
  }
};
</script>
